package com.yopuo.framework.config.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yopuo.common.core.domain.entity.SysUser;
import com.yopuo.common.core.domain.model.LoginUser;
import com.yopuo.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.sql.Timestamp;
import java.time.LocalDateTime;

/**
 * 自动填充字段
 * @author zzh 
 */
public class MyMetaObjectHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        if (user != null) {
            Long userId = user.getUserId();
            this.strictInsertFill(metaObject, "createBy", () -> userId, Long.class);
            this.strictInsertFill(metaObject, "createTime", () -> Timestamp.valueOf(LocalDateTime.now()), Timestamp.class);
//            this.strictInsertFill(metaObject, "updateBy", () -> userId, Long.class);
//            this.strictInsertFill(metaObject, "updateTime", () -> Timestamp.valueOf(LocalDateTime.now()), Timestamp.class);
        }
    }


    @Override
    public void updateFill(MetaObject metaObject) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        if (user != null) {
            Long userId = user.getUserId();
            this.strictUpdateFill(metaObject, "updateBy", () -> userId, Long.class);
            this.strictUpdateFill(metaObject, "updateTime", () -> Timestamp.valueOf(LocalDateTime.now()), Timestamp.class);
        }
    }
}
